package com.zwh.word.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.zwh.word.entity.TbContractPlanItemDto;
import com.zwh.word.entity.TbContractPlanVo;
import com.zwh.word.util.WordUtil;

import cn.hutool.core.net.URLEncodeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * word导出接口层
 * @author LiuXiaoYu ZhangLiXiang
 */
@RestController
@RequestMapping("/word")
@Slf4j
public class WordController {


    /**
     * 测试 简单模板变量、简单列表导出
     * @param response
     */
    @GetMapping("/test")
    public void test(HttpServletResponse response) throws FileNotFoundException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncodeUtil.encode("分包计划报审表导出.docx"));
        /* word模板地址*/
        InputStream inputStream = WordController.class.getClassLoader().getResourceAsStream("wordTemplate/test.docx");

//        Map<String, Object> map = new HashMap<>();

        TbContractPlanVo vo = new TbContractPlanVo();
        vo.setProjectName("测试项目名称20240321");
        vo.setProCode("测试项目编号-20240321");
        vo.setSupervisionDepartment("监理项目部名称");
        List<TbContractPlanItemDto> itemDtoList = new ArrayList<>();
        for(int i = 0; i < 5; i++) {
            TbContractPlanItemDto dto = new TbContractPlanItemDto();
            dto.setSerialNumber((long) (i+1));
            dto.setSubcontractRang("分包范围"+i);
            dto.setSubcontractContent("分包工作量"+i);
            dto.setSubcontractType("劳务分包");
            dto.setProcurementMode("分包采购方式"+i);
            dto.setItemAmount(new BigDecimal("10.3569").multiply(new BigDecimal(i+1)));
            itemDtoList.add(dto);
        }
        vo.setItems(itemDtoList);
        DecimalFormat format = new DecimalFormat("#.##");

//        map.
        /*-------------------------策略渲染----------------------------------*/
        // 表格行循环策略
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                // 列表数据绑定填充策略
                .bind("items", policy)
                .build();

        XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(vo);
        //这里进行导出
//        File file = new File("F:/tmp/20240327.docx");
//        if (!file.getParentFile().exists()) {
//            file.mkdirs();
//        }

        WordUtil.downloadWord(response,template);
    }


}
